import store from '@/store/index.js'
import {base_url} from '@/api/config.js'

const http = (config) => {

	const baseUrl = base_url
	config.url = baseUrl + config.url
	config.header = config.header || {
		'Content-Type':'application/json;charset=utf-8'
	}
	config = requestInterceptors(config)
	return new Promise((resolve, reject) => {
		uni.request(config)
			.then(res => {
				let [error, resp] = res
				let response = responseInterceptors(resp)
				resolve(response)
			})
			.catch(err => {
				errorHandle(err)
				reject(err)
			})
	})


}



const tansParams = (params) => {
	let result = ''
	for (const propName of Object.keys(params)) {
		const value = params[propName];
		var part = encodeURIComponent(propName) + "=";
		if (value !== null && value !== "" && typeof(value) !== "undefined") {
			if (typeof value === 'object') {
				for (const key of Object.keys(value)) {
					if (value[key] !== null && value[key] !== "" && typeof(value[key]) !== 'undefined') {
						let params = propName + '[' + key + ']';
						var subPart = encodeURIComponent(params) + "=";
						result += subPart + encodeURIComponent(value[key]) + "&";
					}
				}
			} else {
				result += part + encodeURIComponent(value) + "&";
			}
		}
	}
	return result
}

const requestInterceptors = (config) => {
	// 是否需要设置 token
	const isToken = (config.header || {}).isToken === false
	// 是否需要防止数据重复提交
	const isRepeatSubmit = (config.header || {}).repeatSubmit === false
	if (!isToken && store?.state?.user?.token) {
		config.header['Authorization'] = 'Bearer ' + store.state.user.token // 让每个请求携带自定义token 请根据实际情况自行修改
	}

	// get请求映射params参数
	if ((config.method === 'get' || config.method === 'put') && config.params) {
		let url = config.url + '?' + tansParams(config.params);
		url = url.slice(0, -1);
		config.params = {};
		config.url = url;
	}
	if (!isRepeatSubmit && (config.method === 'post' || config.method === 'put')) {
		const requestObj = {
			url: config.url,
			data: typeof config.data === 'object' ? JSON.stringify(config.data) : config.data,
			time: new Date().getTime()
		}

		const sessionObj = uni.getStorageSync('sessionObj')
		if (sessionObj === undefined || sessionObj === null || sessionObj === '') {
			uni.setStorageSync('sessionObj', requestObj)
		} else {
			const s_url = sessionObj.url; // 请求地址
			const s_data = sessionObj.data; // 请求数据
			const s_time = sessionObj.time; // 请求时间
			const interval = 1000; // 间隔时间(ms)，小于此时间视为重复提交
			if (s_data === requestObj.data && requestObj.time - s_time < interval && s_url === requestObj.url) {
				const message = '数据正在处理，请勿重复提交';
				return Promise.reject(new Error(message))
			} else {
				uni.setStorageSync('sessionObj', requestObj)
			}
		}
	}
	return config
}

const responseInterceptors = (res) => {

	// 未设置状态码则默认成功状态
	const code = res.data.code || 200
	// 获取错误信息
	const msg = res.data.msg
	
	if(code === 401){
		uni.navigateTo({
			url: '/pages/user/login/login'
		})
	}else if (code && code !== 200) {
		uni.showToast({
			title: msg,
			icon: 'error',
			duration: 2000
		})
		return Promise.reject('error')
	}  else {
		return res.data
	}

	
}

const errorHandle = (err) => {
	console.log(err)
}

export default http